package com.share.device.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.share.common.core.domain.R;
import com.share.common.core.web.controller.BaseController;
import com.share.common.core.web.domain.AjaxResult;
import com.share.device.domain.RegionLocation;
import com.share.device.service.IRegionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "地区信息接口管理")
@RestController
@RequestMapping("/region")
@Slf4j
public class RegionController extends BaseController {

    @Autowired
    private IRegionService regionService;

    @Operation(summary = "根据上级code获取下级数据列表")
    @GetMapping(value = "/treeSelect/{code}")
    public AjaxResult treeSelect(@PathVariable String code) {
                return success(regionService.treeSelect(code));
    }
    @GetMapping("/location")
    public R<RegionLocation> getLocation(
            @RequestParam("districtCode") String districtCode
    ) {
        try {
            log.info("获取地区经纬度，地区编码：{}", districtCode);

            // 先从数据库查询
            RegionLocation location = null;

            // 调用腾讯地图API
            String url = String.format(
                    "https://apis.map.qq.com/ws/geocoder/v1/?address=%s&key=%s",
                    districtCode,
                    "72QBZ-BWA6B-RMHU2-N5T3U-YG3BE-K3FIU"
            );

            log.info("调用腾讯地图API，URL：{}", url);

            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpGet request = new HttpGet(url);
                try (CloseableHttpResponse response = client.execute(request)) {
                    String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                    log.info("腾讯地图API响应：{}", result);


                    JSONObject jsonResponse = JSON.parseObject(result);

                    if (jsonResponse.getInteger("status") == 0) {
                        JSONObject resultObj = jsonResponse.getJSONObject("result");
                        JSONObject locationObj = resultObj.getJSONObject("location");

                        location = new RegionLocation();
                        location.setDistrictCode(districtCode);
                        location.setLatitude(locationObj.getDouble("lat"));
                        location.setLongitude(locationObj.getDouble("lng"));
                        location.setFormattedAddress(
                                resultObj.getString("formatted_addresses")
                        );

                        log.info("成功获取：{}", location);
                        return R.ok(location);
                    }
                }
            }

            log.warn("获取地区经纬度失败，使用默认值");
            return R.ok(getDefaultLocation());
        } catch (Exception e) {
            log.error("获取地区经纬度异常", e);
            return R.ok(getDefaultLocation());
        }
    }

    private RegionLocation getDefaultLocation() {
        RegionLocation defaultLocation = new RegionLocation();
        defaultLocation.setLatitude(39.9042); // 默认北京天安门坐标
        defaultLocation.setLongitude(116.4074);
        defaultLocation.setFormattedAddress("北京市东城区天安门");
        return defaultLocation;
    }
}
